package com.example.markdownmindmap.controller;

import com.example.markdownmindmap.entity.MindMapNode;
import com.example.markdownmindmap.service.MarkdownToMindMapService;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Markdown转换控制器
 */
@RestController
@RequestMapping("/api/markdown")
@Slf4j
public class MarkdownController {
    
    private final MarkdownToMindMapService converterService;
    
    @Autowired
    public MarkdownController(MarkdownToMindMapService converterService) {
        this.converterService = converterService;
    }
    
    /**
     * 通过文本转换
     */
    @PostMapping("/to-mindmap")
    public ResponseEntity<MindMapNode> convertMarkdown(@RequestBody String markdown, @RequestParam String fileName) {
        MindMapNode mindMap = converterService.convert(markdown, fileName);
        log.info("转换后的思维导图: {}", mindMap);
        return ResponseEntity.ok(mindMap);
    }
    
    /**
     * 测试用例接口
     */
    @GetMapping("/test")
    public ResponseEntity<MindMapNode> testConversion() {
        String testMarkdown = "# 标题1\n" +
                              "## 标题1.1\n" +
                              "### 标题1.1.1\n" +
                              "## 标题1.2\n" +
                              "# 标题2\n" +
                              "## 标题2.1\n";
        
        // 使用测试文件名
        MindMapNode mindMap = converterService.convert(testMarkdown, "测试文档");
        log.info("测试用例转换后的思维导图: {}", mindMap);
        return ResponseEntity.ok(mindMap);
    }
    
    /**
     * 上传Markdown文件并转换为思维导图JSON
     */
    @PostMapping("/upload")
    public ResponseEntity<MindMapNode> uploadMarkdown(@RequestParam("file") MultipartFile file) {
        try {
            // 读取文件内容
            String markdown = new String(file.getBytes(), StandardCharsets.UTF_8);
            
            // 转换为思维导图
            // 获取上传文件的原始名称
            String fileName = file.getOriginalFilename();
            // 移除文件扩展名
            if (fileName != null && fileName.contains(".")) {
                fileName = fileName.substring(0, fileName.lastIndexOf('.'));
            }
            MindMapNode mindMap = converterService.convert(markdown, fileName != null ? fileName : "未命名文档");
                    log.info("测试用例转换后的思维导图: {}", mindMap);

            return new ResponseEntity<>(mindMap, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
